package org.ruanjj.margearray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        List<int[]> mergeList = new ArrayList<>();
        for(int i = 0; i < intervals.length; i++){
            int L = intervals[i][0];  int R = intervals[i][1];
            if(mergeList.size() == 0 || mergeList.get(mergeList.size()-1)[1] < L){
                mergeList.add(intervals[i]);
            }else{
                mergeList.get(mergeList.size()-1)[1] = Math.max(R,mergeList.get(mergeList.size()-1)[1]) ;
            }
        }
        return  mergeList.toArray(new int[mergeList.size()][]);
    }
}
